from django.db import models
from django.contrib.auth.models import AbstractUser
import shortuuid
from  backend.settings import QINIU_DOMAIN
def generate_uid():
    return shortuuid.ShortUUID(alphabet="0123456789abcdefghijklmnopqrstuvwxyz").random(length=12)

class CustomUser(AbstractUser):
    @property
    def avatar_url(self):
        if not self.avatar_key:
            return None 
        from utils.qiniu_tools import ImageHandler
        handler = ImageHandler()
        return handler.get_public_url(self.avatar_key)  # 直接使用公有URL
    
    uid = models.CharField(
        max_length=12,
        unique=True,
        default=generate_uid,
        verbose_name="业务ID"
    )
    phone = models.CharField(max_length=20, unique=True, verbose_name="手机号")
    register_time = models.DateTimeField(auto_now_add=True, verbose_name="注册时间")
    credit_score = models.DecimalField(
        max_digits=3,
        decimal_places=1,
        default=5.0,
        verbose_name="信用分",
    )
    avatar_key = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        verbose_name="头像相对路径",
    )
    

    class Meta:
        db_table = 'USERS'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username
    @classmethod
    def is_username_taken(cls, username):
        """检查用户名是否已存在"""
        return cls.objects.filter(username=username).exists()

class Address(models.Model):
    """
    用户地址模型（对应数据库表 ADDRESS）
    """
    user = models.ForeignKey(
        CustomUser,
        on_delete=models.CASCADE,
        db_column='user_id',  # 显式指定数据库列名
        verbose_name='所属用户',
        db_index=False,  # 显式禁用外键自动索引
        related_name='addresses'
        )
    """这个问题是因为在Django Admin中默认会显示模型对象的__str__()方法返回的值。在CustomUser模型中，__str__()方法返回的是username字段,所以地址的user字段显示的是用户名。"""
    receiver_name = models.CharField(max_length=50, verbose_name='收件人姓名')
    receiver_phone = models.CharField(max_length=20, verbose_name='收件人电话')
    detail = models.CharField(max_length=255, verbose_name='详细地址')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    is_default = models.BooleanField(default=False, verbose_name='默认地址')

    class Meta:
        db_table = 'ADDRESS'  # 显式指定表名
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name
        indexes = [
            models.Index(fields=['user'], name='idx_address_user')  # 创建外键索引
        ]

    def __str__(self):
        return f"{self.receiver_name} - {self.detail[:20]}..."
    

class SchoolProfile(models.Model):
    user = models.OneToOneField(
        CustomUser,
        on_delete=models.CASCADE,
        db_column='user_id',
        related_name='school_profile'
    )
    ROLE_CHOICES = (
        (0, '本科生'),
        (1, '研究生/博士生'),
        (2, '教职工')
    )
    role = models.SmallIntegerField(choices=ROLE_CHOICES,verbose_name = '用户角色')
    student_id = models.CharField(max_length=15, null=True, blank=True,verbose_name = '学号')  # 学号示例：202312345678
    staff_id = models.CharField(max_length=12, null=True, blank=True,verbose_name = '工号')   # 工号示例：ZG202403
    campus = models.ForeignKey(
        'Campus',
        on_delete=models.PROTECT,
        verbose_name="所属校区"
    )
    class Meta:
        indexes = [
            # 达梦要求索引名全局唯一，添加表名前缀
            # 联合索引调整为单独索引（达梦联合索引使用限制较多）
            models.Index(fields=['student_id'], name='sch_prof_stuid_idx'),
            models.Index(fields=['staff_id'], name='sch_prof_staffid_idx'),
        ]


class Campus(models.Model):
    name = models.CharField(max_length=20)  # 如"珠海校区"
    code = models.CharField(max_length=4)  # 如"ZH01"
    address = models.TextField()
    class Meta:
        constraints = [
            # 确保校区编码唯一
            models.UniqueConstraint(fields=['code'], name='uniq_campus_code')
        ]
        indexes = [
            # 达梦索引名全局唯一化处理
            models.Index(fields=['name'], name='campus_name_idx'),
        ]